import { useModel } from '@@/exports';
import { useEffect, useState } from 'react';
import './ChatDialog.css';

interface SocketState {
  socket: null | WebSocket;
}

function WebSocketComponent() {
  const [socket, setSocket] = useState<SocketState>({
    socket: null,
  });
  const [messages, setMessages] = useState([]);
  const [messageInput, setMessageInput] = useState('');
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};

  useEffect(() => {
    const newSocket = new WebSocket('ws://localhost:8101/api//chat');
    setSocket(newSocket);

    newSocket.addEventListener('open', (event) => {
      console.log('WebSocket connection opened');
    });

    newSocket.addEventListener('message', (event) => {
      const receivedMessage = JSON.parse(event.data);
      //将浏览器发送的消息设置到messages中
      setMessages((prevMessages) => [...prevMessages, receivedMessage]);
    });

    newSocket.addEventListener('close', (event) => {
      console.log('WebSocket connection closed');
    });

    // 清理函数，关闭WebSocket连接
    return () => {
      if (newSocket.readyState === WebSocket.OPEN) {
        newSocket.close();
      }
    };
  }, []);

  const sendMessage = () => {
    if (socket && socket.readyState === WebSocket.OPEN && messageInput.trim()) {
      const messageData = {
        content: messageInput,
        sender: currentUser.userName,
      };
      //将发生的消息设置到messages中
      setMessages([...messages, messageData]);
      socket.send(JSON.stringify(messageData));
      setMessageInput('');
    }
  };

  return (
    <div className="chat-room">
      {/* Message List */}
      <ul className="message-list" style={{ overflowY: 'auto', maxHeight: '300px' }}>
        {messages.map((msg, index) => (
          <li key={index} className={`message ${msg.sender === 'You' ? 'sent' : 'received'}`}>
            {msg.sender === '0' ? '' : msg.sender + ':'}
            {msg.content}
          </li>
        ))}
      </ul>

      {/* Input and Send Button */}
      <div className="input-group fixed-input-group">
        <input
          type="text"
          placeholder="Type your message..."
          value={messageInput}
          onChange={(e) => setMessageInput(e.target.value)}
        />
        <button type="button" onClick={sendMessage}>
          Send
        </button>
      </div>
    </div>
  );
}

export default WebSocketComponent;
